package com.example.its2021606134chh;

import android.os.Handler;
import android.os.Looper;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @ClassName: HttpUtil$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 2021/6/18$
 * @Version: 1.0
 */
public class HttpUtil {
    public static OkHttpClient client;  //创建 client 对象

    static {//静态代码块 进行初始化
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.writeTimeout(15, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.connectTimeout(15, TimeUnit.SECONDS);
        client = builder.build();
    }

//    创建 RequestBody 对象
    public static JSONObject buildJSON(String[] keys, Object... values) {//构建JSON参数
        JSONObject jsonObject =null;
        try {
            jsonObject = new JSONObject();
            for (int i = 0; i < keys.length; i++) {
                jsonObject.put(keys[i], values[i]);
            }
        } catch (Exception e) {
            jsonObject = null;
        }
        return jsonObject;
    }

    public static RequestBody buildBody(JSONObject json) {  //创建RequestBody对象
        return RequestBody.create(MediaType.parse("application/json; charset =utf-8"), json.toString());
    }

    public static String host = "http://121.9.253.237:8888/traffic/api/v2/";
    public static Request buildRequest(String api, RequestBody body) {  //创建Request对象
        return new Request.Builder().url(host + api).post(body).build();
    }

    public static Call buildCall(Request request) { //创建 call 对象
        return client.newCall(request);
    }

//通过 Call#enqueue(Callback)方法来提交异步请求,并通过 Handler 将获取的数据提交给主线程处理
    public static Handler handler = new Handler(Looper.getMainLooper());    //定义用于更新 UI 主线程的通讯句柄。
    //声明异步回调接口
    public interface AsyncCallBack {
        void onFailure(Exception e);
        void onResponse(String json);
    }
    public static void asyncRequest( final AsyncCallBack callBack,String api,String[] keys, Object...values) {
        JSONObject jsonObject = buildJSON(keys, values); //将参数构建成JSON格式的数据
        RequestBody requestBody = buildBody(jsonObject);//获取 RequestBody 对象
        Request request = buildRequest(api, requestBody);//获取 Request 对象
        Call call=buildCall(request);//获得 Call 呼叫对象
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { //请求失败
                callBack.onFailure(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { //请求成功
                final String json = response.body().string();//获取反馈数据
                handler.post(new Runnable() {   //将对 json 数据的处理提交到主线程
                    @Override
                    public void run() {
                        callBack.onResponse(json);
                    }
                });
            }
        });

    }
    public static String syncRequest(String api,String[] keys, Object...values) throws Exception {
        JSONObject jsonObject= buildJSON(keys, values);
        RequestBody requestBody=buildBody(jsonObject);
        Request request = buildRequest(api, requestBody);
        Call call=buildCall(request);
        Response response=call.execute();
        return response.body().string();
    }


    }
